<template>
    <view style="display: flex;flex-direction: column;align-items: center;margin-top: 20rpx;position: relative;">

        <posterShow ref="posterShow" v-if="posterObj.isShow" :backgroundUrl="posterObj.backgroundUrl"
            :qrCodeUrl="posterObj.qrCodeUrl" :avatarUrl="posterObj.avatarUrl" :name="posterObj.name"
            :telephone="posterObj.telephone" :showCard="posterObj.isShowNameCard" @success="onPosterSuccess">
        </posterShow>
        <view class="addImageContainer" v-else @click="onPopupOpen">
            <image class="icon" src="../static/image/poster_edit_icon_add.png" mode=""></image>
            点击添加图片制作海报
        </view>
        <view class="changeImage" v-if="posterObj.isShow" @click="onPopupOpen" >
            更换图片
        </view>
        <view class="setContainer">
            <view class="title">
                海报名称
                <textarea class="text" auto-height="true" maxlength="-1" v-model="posterObj.title" placeholder="请输入海报名称">
                 </textarea>
            </view>
            <view class="line">

            </view>
            <view class="title" @click="onOpenPosterPopup">
                海报类型
                <view class="typeContainer" v-if="posterObj.type>=0">
                    {{posterObj.type==0?'名片':(posterObj.type==1?'文章':'活动')}}
                    <image class="icon" src="../static/image/poster_icon_arrow_r.png" mode=""></image>
                </view>
                <view class="typeContainer" v-else>
                    添加海报类型
                    <image class="icon" src="../static/image/poster_icon_arrow_r.png" mode=""></image>
                </view>
            </view>
            <view class="title" v-if="(posterObj.type>0)&&(posterObj.typeTitle.length>0)" @click="gotoDetailPage">
                {{posterObj.type==1?'文章':'活动'}}详情
                <view class="typeContainer">
                    <view class="text-1line-ellipsis" style="max-width: 400rpx;color: #333333;">
                        {{posterObj.typeTitle}}
                    </view>
                    <image class="icon" src="../static/image/posterArrow.png" mode=""></image>
                </view>
            </view>
            <view class="line">

            </view>
            <view class="title">
                <view style="margin-right: 33rpx;">
                    头像显示
                </view>
                <u-switch v-model="posterObj.isShowNameCard"></u-switch>
            </view>
            <view class="line" v-if="hasAllPosterParams">

            </view>

            <view class="tabBottom" v-if="hasAllPosterParams">
                <image @click="onDeletePoster" v-if="posterObj.posterId.length>0" class="left" src="../static/image/poster_icon_del.png" mode=""></image>
                <view  v-else class="left">
                    
                </view>
                <view class="middle" @click="savePoster">
                    保存海报
                </view>
                <image @click="downloadPoster" v-if="isChangePoster==false" class="right" src="../static/image/poster_icon_download.png" mode=""></image>
            </view>

            <view class="bottom">

            </view>
        </view>

        <u-popup :show="showBottomPopup" @close="showBottomPopup=false" mode="bottom" border-radius="40">
            <view class="popupContainer">
                <view class="wrapper camera" @click="selectFromCameraAlbum('camera')">
                    <image class="icon" src="../static/image/article_frame_icon_photo.png" mode=""></image>
                    拍照上传
                </view>
                <view class="line">

                </view>
                <view class="wrapper album" @click="selectFromCameraAlbum('album')">
                    <image class="icon" src="../static/image/article_frame_icon_atlas.png" mode=""></image>
                    相册上传
                </view>
                <view class="line">

                </view>
                <view class="wrapper cancel" @click="onPopupClose">
                    取消
                </view>
            </view>
        </u-popup>

        <u-popup :show="showPosterPopup" @close="showPosterPopup=false" mode="bottom" border-radius="40">
            <view class="posterPopupContainer">
                <image @click="closePosterPopup" class="close" src="../static/image/frame_top_icon_close.png" mode="">
                </image>
                <view class="title">
                    海报类型
                </view>
                <view class="wrapper">
                    <view class="item" @click="onPosterTypeSelect(0)">
                        <image v-if="posterPopupTypeSelect==0" class="select" src="../static/image/poster_type_icon_gou.png" mode=""></image>
                        <image class="icon" src="../static/image/poster_type_icon_1.png" mode=""></image>
                        名片
                    </view>
                    <view class="item" @click="onPosterTypeSelect(1)">
                        <image v-if="posterPopupTypeSelect==1" class="select" src="../static/image/poster_type_icon_gou.png" mode=""></image>
                        <image class="icon" src="../static/image/poster_type_icon_2.png" mode=""></image>
                        文章
                    </view>
                    <view class="item" @click="onPosterTypeSelect(2)">
                        <image v-if="posterPopupTypeSelect==2" class="select" src="../static/image/poster_type_icon_gou.png" mode=""></image>
                        <image class="icon" src="../static/image/poster_type_icon_3.png" mode=""></image>
                        活动
                    </view>
                </view>
                <view class="confirmBtn" @click="onConfirmPosterPopup">
                    确定
                </view>
            </view>
        </u-popup>

        <kps-image-cutter @ok="onSave" @cancel="onCancle" :url="srcImgUrl" :fixed="true" :width="cutWidth"
            :height="cutHeight"></kps-image-cutter>
    </view>
</template>

<script>
    import {
        mapState,
        mapMutations,
        mapActions
    } from 'vuex';
    let that = null
    let App = getApp();
    const Config = require("@/config.js")
    const api = require("@/static/js/api.js")
    const utils = require("@/static/js/utils.js")
    import posterShow from "../components/poster/posterShow.vue"
    import kpsImageCutter from "../components/ksp-image-cutter/ksp-image-cutter.vue";
    export default {
        components: {
            posterShow,
            kpsImageCutter
        },
        computed: {
            ...mapState({
                hasLogin: state => state.userInfo.hasLogin,
                isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
                isAuthPhone: state => state.userInfo.isAuthPhone,
                isSeller: state => state.userInfo.isSeller,
                avatarUrl: state => state.userInfo.avatarUrl,
                nickName: state => state.userInfo.nickName,
                telephone: state => state.userInfo.telephone,
                openId: state => state.userInfo.openId,
                employeeId: state => state.userInfo.employeeId,
                shopEmployee: state => state.userInfo.shopEmployee,
            }),
            isChangePoster(){
                let that = this
                if ((that.posterObjBackup.backgroundUrl !=that.posterObj.backgroundUrl)
                   || (that.posterObjBackup.title !=that.posterObj.title)
                   || (that.posterObjBackup.type !=that.posterObj.type)
                   || (that.posterObjBackup.typeValue !=that.posterObj.typeValue)
                   || (that.posterObjBackup.isShowNameCard !=that.posterObj.isShowNameCard)
                ){
                    return true;
                }else{
                    return false;
                }    
                
            },
            hasAllPosterParams(){
                let that = this
                if ((that.posterObj.backgroundUrl.length>0)
                   && (that.posterObj.title.length>0)
                   && (that.posterObj.type>=0)
                   && (that.posterObj.type==0||that.posterObj.typeValue.length>0)
                ){
                    return true;
                }else{
                    return false;
                } 
            }
        },
        data() {
            return {
                posterObjBackup: {
                    isShow: false,
                    posterId: "",
                    title: "",
                    backgroundUrl: "",
                    qrCodeUrl: "",
                    avatarUrl: "",
                    name: "",
                    telephone: "",
                    type: -1, // 海报类型  0名片，1文章，2活动
                    typeTitle: "",
                    typeValue: "",
                    isShowNameCard: false,
                    showPicture: "",
                },
                
                posterObj: {
                    isShow: false,
                    posterId: "",
                    title: "",
                    backgroundUrl: "",
                    qrCodeUrl: "",
                    avatarUrl: "",
                    name: "",
                    telephone: "",
                    type: -1, // 海报类型  0名片，1文章，2活动
                    typeTitle: "",
                    typeValue: "",
                    isShowNameCard: false,
                    showPicture: "",
                },
                

                waitForPosterSuccess: false,

                //===背景裁剪
                cutWidth: uni.upx2px(620),
                cutHeight: uni.upx2px(930),
                srcImgUrl: "",
                cutedImgUrl: "",
                showBottomPopup: false,
                showPosterPopup: false,
                posterPopupTypeSelect: -1,
            }
        },
     
        onLoad(options) {
            that = this;
            
            that.resetSelectObj();
            
            if (that.shopEmployee&&that.shopEmployee.qrCode){
                that.posterObj.qrCodeUrl = that.shopEmployee.qrCode||""
            }
            
            if (that.shopEmployee&&that.shopEmployee.employee){
                that.posterObj.name = that.shopEmployee.employee.realname
                that.posterObj.telephone = that.shopEmployee.employee.phone
                that.posterObj.avatarUrl = that.shopEmployee.employee.avatar
            }    
                
            if (options.id && options.id.length > 0) {
                that.posterObj.posterId = options.id;
                that.posterObj.isShow = true;
                that.getPoster(options.id);
            }
        },

        onShow() {
            this.freshSelectObj()
        },
        
        methods: {
            resetSelectObj(){
                App.globalData.selectObj.type = -1;
                App.globalData.selectObj.typeValue = "";
                App.globalData.selectObj.typeTitle = '';
            },
            freshSelectObj(){               
                 that.posterObj.type = App.globalData.selectObj.type;
                 that.posterObj.typeValue = App.globalData.selectObj.typeValue;
                 that.posterObj.typeTitle = App.globalData.selectObj.typeTitle;
            },

            setPosterObj(res){
                console.log("setPosterObj:",res.data)
                that.posterObj.showPicture = res.data.showPicture;
                that.posterObj.posterId = res.data.id;
                that.posterObj.backgroundUrl = res.data.picture;
                that.posterObj.qrCodeUrl = res.data.qrCode||that.posterObj.qrCodeUrl;
                that.posterObj.title = res.data.name;
                
                that.posterObj.type = res.data.type;
                that.posterObj.typeValue = res.data.typeValue;
                that.posterObj.typeTitle = res.data.title;
                
                App.globalData.selectObj.type = res.data.type;
                App.globalData.selectObj.typeValue = res.data.typeValue;
                App.globalData.selectObj.typeTitle = res.data.title;
                
                
                if (res.data.showCard == 1) {
                    that.posterObj.isShowNameCard = true
                }
                
                that.posterObjBackup.backgroundUrl = that.posterObj.backgroundUrl
                that.posterObjBackup.type = that.posterObj.type
                that.posterObjBackup.typeValue = that.posterObj.typeValue
                that.posterObjBackup.title = that.posterObj.title
                that.posterObjBackup.isShowNameCard = that.posterObj.isShowNameCard
                
                
                setTimeout(() => {
                    that.$refs.posterShow.onceFreshCanvas();
                }, 100)
            },
            
            getPoster(id) {
                let that = this
                api.getPoster({
                    interfaceName: id,
                    param: {}
                }).then(res => {
                    console.log(res)
                    if (res.success) {
                        that.setPosterObj(res)
                    }
                })
            },
            updatePoster(){
                uni.showLoading({
                    title: "保存海报中...",
                })
                api.updatePoster({
                    param: {
                        id: that.posterObj.posterId,
                        name:that.posterObj.title,
                        picture: that.posterObj.backgroundUrl,
                        showCard: that.posterObj.isShowNameCard?"1":"0",
                        type: that.posterObj.type,
                        typeValue: that.posterObj.typeValue
                    }
                }).then(res => {
                    uni.hideLoading()
                    console.log(res)
                    if (res.success) {
                        that.setPosterObj(res)
                        uni.showModal({
                            title: '提示',
                            showCancel:false,
                            content: '保存海报成功，可以下载了！',
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用户点击确定');
                                } else if (res.cancel) {
                                    console.log('用户点击取消');
                                }
                            }
                        });
                        typeof callback == 'function' && callback();
                    }
                }).catch(()=>{
                    uni.hideLoading()
                })
            },
            addPoster(){
                uni.showLoading({
                    title: "保存海报中...",
                })
                api.addPoster({
                    param: {
                        name:that.posterObj.title,
                        picture: that.posterObj.backgroundUrl,
                        showCard: that.posterObj.isShowNameCard?"1":"0",
                        type: that.posterObj.type,
                        typeValue: that.posterObj.typeValue
                    }
                }).then(res => {
                    console.log(res)
                    uni.hideLoading()
                    if (res.success) {
                        that.setPosterObj(res)
                        uni.showModal({
                            title: '提示',
                            showCancel:false,
                            content: '保存海报成功，可以下载了！',
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用户点击确定');
                                } else if (res.cancel) {
                                    console.log('用户点击取消');
                                }
                            }
                        });
                        typeof callback == 'function' && callback();
                    }
                }).catch(()=>{
                    uni.hideLoading()
                })
            },

            onPosterSuccess() {
                this.waitForPosterSuccess = true;
            },
            gotoDetailPage() {
                if (that.posterObj.typeValue.length > 0) {
                    if (that.posterObj.type == 1) {
                        console.log("gotoDetailPage")
                        uni.navigateTo({
                            url: "../article/articleDetail?id=" + that.posterObj.typeValue
                        })
                    } else if (that.posterObj.type == 2) {
                        uni.navigateTo({
                            url: "../activityDetail/activityDetail?id=" + that.posterObj.typeValue
                        })
                    }

                }
            },
            onDeletePoster(){
                uni.showModal({
                    title: '提示',
                    showCancel:true,
                    content: '确定要删除当前海报吗？',
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            api.deletePoster({
                                interfaceName: that.posterObj.posterId,
                                param: {}
                            }).then(res => {
                                console.log(res)
                                if (res.success) {
                                    uni.showToast({
                                        title:'海报删除成功！',
                                        icon:"none",
                                    })
                                    uni.navigateBack({
                                        
                                    })
                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
                

                
            },
            savePoster() {
                if (!(that.posterObj.title.length>0)){
                    uni.showToast({
                        title:"需要填写海报标题",
                        icon: "none",
                    })
                    return
                }
                if (!(that.posterObj.backgroundUrl.length>0)){
                    uni.showToast({
                        title:"未选择海报背景图",
                        icon: "none",
                    })
                    return
                }
                if (that.posterObj.type<0){
                    uni.showToast({
                        title:"未选择海报类型",
                        icon: "none",
                    })
                    return
                }


                if (that.posterObj.posterId.length>0){
                    that.updatePoster();
                }else{
                    that.addPoster();
                }
            },
            downloadPoster() {
                console.log("downloadPoster")
                // this.$refs.posterShow.savePoster(); //===本地保存
                if (that.posterObj.showPicture.length>0){
                    uni.getImageInfo({
                    	src: that.posterObj.showPicture,
                    	success: function(image) {
                    		console.log('图片信息：', JSON.stringify(image));
                    		uni.saveImageToPhotosAlbum({
                    			filePath: image.path,
                    			success: function() {
                    				console.log('save success');
                    				uni.showToast({
                    					title: '图片保存成功',
                    					icon: 'none',
                    					duration: 2200
                    				});
                    			}
                    		});
                    	},
                    	fail(err) {
                    		
                    	}
                    });
                }
                
            },

            //====Oss上传图片
            //===  https://www.cnblogs.com/fan-zha/p/11356154.html
            getOssSignature(path, callback) {
                api.getOssSignature({
                    param: {
                        dir: Config.productId+"/"+that.openId,
                    }
                }).then(res => {
                    console.log(res)
                    if (res.success) {
                        typeof callback == 'function' && callback(path, res.data);
                    }
                })
            },
            uploadImage(path, callback) {
                function uploadConduct(path, signTmp) {
                    let sign = signTmp;
                    let imageSrc = path;
                    let fileName = Config.productId+"/"+that.openId + '/' + "poster" + utils.uuid()+'.png'; // 自定义上传后的文件名称
                    console.log(sign, imageSrc, fileName)
                    let uploadTask = uni.uploadFile({
                        url: sign.host,
                        filePath: imageSrc,
                        fileType: 'image',
                        name: 'file',
                        formData: {
                            name: imageSrc,
                            'key': fileName,
                            'policy': sign.policy,
                            'OSSAccessKeyId': sign.accessId,
                            'success_action_status': '200',
                            //让服务端返回200,不然，默认会返回204
                            'signature': sign.signature,
                        },
                        success: (res) => {
                            console.log('uploadImage success, res is:', res)
                            uni.showToast({
                                title: '上传成功',
                                icon: 'success',
                                duration: 1000
                            });
                            if (res.statusCode == 200) {
                                var path = sign.host + fileName;
                                typeof callback == 'function' && callback(path);
                            }
                            that.$emit('imgUploaded', {
                                data: sign.host + fileName,
                                authId: that.authId
                            });
                            uni.hideLoading()
                        },
                        fail: (err) => {
                            uni.hideLoading()
                            console.log('uploadImage fail', err);
                            uni.showModal({
                                content: err.errMsg,
                                showCancel: false
                            });
                        }
                    });
                    uploadTask.onProgressUpdate((res) => {
                        console.log("上传进度" + res.progress);
                        that.progress = res.progress;
                    });
                }


                uni.showLoading({
                    title: "上传图片"
                })
                that.getOssSignature(path, (path, signTmp) => {
                    uploadConduct(path, signTmp)
                })
                // this.$emit('imgUploaded', {data: files.tempFilePaths[0], authId: this.authId});
            },
            //=====背景编辑
            onPopupOpen() {
                this.showBottomPopup = true;
            },
            onPopupClose() {
                this.showBottomPopup = false;
            },
            selectFromCameraAlbum(type) {
                this.showBottomPopup = false;
                uni.chooseImage({
                    count: 1,
                    sourceType: [type],
                    success: (res) => {
                        var path = res.tempFilePaths[0];
                        that.srcImgUrl = res.tempFilePaths[0];
                        // 实际项目中应上传图片到服务一起，获取url后再添加
                        // that.articleObj.coverImage = path;

                    }
                })
            },
            onDeleteCoverImage() {
                that.articleObj.coverImage = "";
            },

            onSave(ev) {
                var path = ev.path;
                // that.getOssSignature(path, (path, sign) => {
                //     this.uploadImage(path, sign)
                // })
                that.uploadImage(path, (url) => {
                    that.posterObj.backgroundUrl = url
                    that.posterObj.isShow = true
                })
                this.srcImgUrl = "";
            },
            onCancle() {
                // url设置为空，隐藏控件
                this.srcImgUrl = "";
            },
            //=======海报类型弹窗
            onOpenPosterPopup(){
                console.log("onOpenPosterPopup")
                that.posterPopupTypeSelect = that.posterObj.type;               
                that.showPosterPopup = true
            },
            onPosterTypeSelect(id){
                that.posterPopupTypeSelect = id;
            },
            onConfirmPosterPopup(){
                console.log("onConfirmPosterPopup")
                that.posterObj.type = that.posterPopupTypeSelect 
                that.showPosterPopup = false;
                if (that.posterObj.type == 1){
                    uni.navigateTo({
                        url:"./selectArticle"
                    })
                }
                if (that.posterObj.type == 2){
                    uni.navigateTo({
                        url:"./selectActivity"
                    })
                }
            },
            closePosterPopup() {
                that.showPosterPopup = false
            }
            
        }
    }
</script>
<style>
    page {
        background-color: #F3F3F3;
    }
</style>
<style lang="scss">
    .addImageContainer {
        width: 620rpx;
        height: 930rpx;
        background-color: #ffffff;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        color: #999999;

        .icon {
            width: 144rpx;
            height: 144rpx;
            margin-bottom: 44rpx;
        }

    }
    .changeImage{
        width: 132rpx;
        height: 54rpx;
        background-color: #000000;
        border-radius: 0rpx 0rpx 10rpx 10rpx;
        opacity: 0.8;
        position: absolute;
        right: 54rpx;
        top: 0;
        line-height: 54rpx;
        text-align: center;
        font-size: 26rpx;
        color: #ffffff;
    }
    .setContainer {
        width: 750rpx;
        // height: 420rpx;
        background-color: #ffffff;
        padding-left: 28rpx;
        margin-top: 32rpx;

        .title {
            display: flex;
            align-items: center;
            font-size: 30rpx;
            color: #666666;
            margin-top: 41rpx;
            margin-bottom: 32rpx;

            .text {
                width: 450rpx;
                font-size: 30rpx;
                color: #333333;
                margin-left: 33rpx;
            }

            .typeContainer {
                display: flex;
                align-items: center;
                font-size: 30rpx;
                color: #16a5fe;
                margin-left: 33rpx;

                .type {
                    min-width: 60rpx;
                }

                .icon {
                    height: 22rpx;
                    width: 22rpx;
                    margin-left: 12rpx;
                }
            }
        }



        .line {
            width: 722rpx;
            height: 1px;
            background-color: #e3e3e3;
        }

        .tabBottom {
            margin-top: 33rpx;
            margin-bottom: 33rpx;
            width: 100%;
            display: flex;
            // justify-content: center;
            align-items: center;

            // margin-left: 41rpx;
            .left {
                width: 100rpx;
                height: 100rpx;
            }

            .middle {
                width: 360rpx;
                height: 88rpx;
                background-image: linear-gradient(#16a5fe,
                        #16a5fe),
                    linear-gradient(90deg,
                        #24c9ff 0%,
                        #349dee 100%);
                background-blend-mode: normal,
                    normal;
                border-radius: 44rpx;
                font-size: 32rpx;
                color: #ffffff;
                line-height: 88rpx;
                text-align: center;
                margin-left: 62rpx;
                margin-right: 62rpx;
            }

            .right {
                width: 100rpx;
                height: 100rpx;
            }

        }

        .bottom {
            width: 750rpx;
            height: 71rpx;
        }
    }

    .popupContainer {
        .wrapper {
            font-size: 32rpx;
            height: 122rpx;
            width: 750rpx;
            line-height: 122rpx;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;

            .icon {
                width: 44rpx;
                height: 44rpx;
                margin-right: 20rpx;
            }
        }

        .album {
            color: #121212;
        }

        .camera {
            color: #121212;
        }

        .cancel {
            color: #666666;
        }

        .line {
            width: 750rpx;
            height: 1px;
            background-color: #e3e3e3;
        }
    }

    .posterPopupContainer {
        width: 750rpx;
        height: 536rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;

        .close {
            width: 30rpx;
            height: 30rpx;
            padding: 15rpx;
            position: absolute;
            right: 13rpx;
            top: 33rpx;
        }

        .title {
            font-size: 34rpx;
            color: #121212;
            margin-top: 43rpx;
        }

        .wrapper {
            display: flex;
            width: 590rpx;
            margin-top: 81rpx;
            justify-content: space-between;

            .item {
                position: relative;
                font-size: 26rpx;
                color: #333333;
                display: flex;
                flex-direction: column;
                align-items: center;

                .icon {
                    width: 100rpx;
                    height: 100rpx;
                    margin-bottom: 22rpx;
                }

                .select {
                    width: 40rpx;
                    height: 40rpx;
                    position: absolute;
                    top: 0;
                    right: -10rpx;
                }
            }

        }
        .confirmBtn{
            width: 690rpx;
            height: 96rpx;
            background-color: #16a5fe;
            border-radius: 48rpx;
            font-size: 32rpx;
            color: #ffffff;
            line-height: 96rpx;
            text-align: center;
            margin-top: 64rpx;
        }
    }
    
    
</style>
